package org.itstack.engine;

import org.itstack.model.Order;
import org.itstack.OrderEngineBase;
import org.itstack.OrderProcessResult;
import org.itstack.model.aggregates.TreeRich;
import org.itstack.model.vo.TreeNode;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 带缓存的订单引擎
 * 缓存决策结果以提高性能
 */
public class CachedOrderEngine extends OrderEngineBase {
    
    private Map<String, OrderProcessResult> resultCache = new ConcurrentHashMap<>();
    private final int maxCacheSize = 1000; // 最大缓存大小
    
    @Override
    public OrderProcessResult process(Order order, TreeRich treeRich) {
        String cacheKey = generateCacheKey(order, treeRich);
        
        // 检查缓存
        if (resultCache.containsKey(cacheKey)) {
            System.out.println("从缓存获取决策结果: " + cacheKey);
            return resultCache.get(cacheKey);
        }
        
        // 执行决策逻辑
        TreeNode resultNode = engineDecisionMaker(treeRich, order);
        OrderProcessResult result = new OrderProcessResult(
            order.getId(),
            "DECISION_TREE",
            resultNode.getNodeValue() != null ? resultNode.getNodeValue() : "SUCCESS",
            "决策树处理完成，节点ID: " + resultNode.getTreeNodeId()
        );
        
        // 缓存结果
        cacheResult(cacheKey, result);
        
        return result;
    }
    
    private String generateCacheKey(Order order, TreeRich treeRich) {
        return order.getId() + "_" + treeRich.getTreeRoot().getTreeId();
    }
    
    private void cacheResult(String cacheKey, OrderProcessResult result) {
        // 检查缓存大小，如果超过限制则清理
        if (resultCache.size() >= maxCacheSize) {
            clearCache();
        }
        
        resultCache.put(cacheKey, result);
        System.out.println("缓存决策结果: " + cacheKey);
    }
    
    public void clearCache() {
        resultCache.clear();
        System.out.println("缓存已清理");
    }
    
    public int getCacheSize() {
        return resultCache.size();
    }
    
    public boolean isCached(String cacheKey) {
        return resultCache.containsKey(cacheKey);
    }
}
